package hu.test.atacama;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class GPSActivity extends Activity {
	Button sendButton, GPSButton;
	EditText editTextLat, editTextLon, editTextTime, editTextResponseCode,
			editTextSenderID, editTextSerialNumber, editTextServerAddress;

	IntentFilter commServIntentFilter, commServErrorIntentFilter;
	CommServiceReceiver commServiceReceiver = new CommServiceReceiver();
	final Intent commServiceIntent = new Intent();
	final Intent locInfoServiceIntent = new Intent();
	Common common;

	GetLocation gpsService;
	boolean gpsServiceBound = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_get_gpsdata);

		common = Common.getInstance(this);
		commServiceIntent.setClass(getApplicationContext(), CommService.class);
		commServIntentFilter = new IntentFilter(CommService.COMMSERVICE_DONE);
		commServErrorIntentFilter = new IntentFilter(CommService.COMMSERVICE_ERROR);

		locInfoServiceIntent.setClass(getApplicationContext(),
				LocInfoService.class);

		editTextLat = (EditText) findViewById(R.id.edit_gps_lat);
		editTextLon = (EditText) findViewById(R.id.edit_gps_lon);
		editTextTime = (EditText) findViewById(R.id.edit_time_stamp);
		editTextSenderID = (EditText) findViewById(R.id.edit_sender_id);
		editTextSerialNumber = (EditText) findViewById(R.id.edit_serial_number);
		editTextServerAddress = (EditText) findViewById(R.id.edit_server_address);
		editTextResponseCode = (EditText) findViewById(R.id.edit_response_code);

		sendButton = (Button) findViewById(R.id.buttonSend);
		GPSButton = (Button) findViewById(R.id.buttonGPS);

		// refreshTextFields();

		sendButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (editTextLat.getText().length() != 0) {
					sendLocInfoToServer();
				} else {
					common.showAlert("No location info yet!");
				}
			}
		});

		GPSButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (gpsServiceBound) {
					editTextLat.setText(Double.toString(gpsService
							.getLatitude()));
					editTextLon.setText(Double.toString(gpsService
							.getLongitude()));
					editTextTime.setText(Long.toString(gpsService.getTime()));
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.get_gpsdata, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		try {
			switch (item.getItemId()) {
			case R.id.menu_gps_back:
				finish();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		} catch (Exception ex) {
			Toast.makeText(getApplicationContext(),
					"GetGPSData / onOptionsItemSelected: " + ex.toString(),
					Toast.LENGTH_LONG).show();
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		Intent getLocationIntent = new Intent(this, GetLocation.class);
		bindService(getLocationIntent, gpsConnection, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onPause() {
		unregisterReceiver(commServiceReceiver);
		unregisterReceiver(commServiceError);
		unregisterReceiver(locationSentReceiver);
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// common = Common.getInstance(this);
		refreshTextFields();
		registerReceiver(commServiceReceiver, commServIntentFilter);
		registerReceiver(commServiceError, commServErrorIntentFilter);
		registerReceiver(locationSentReceiver, commServIntentFilter);
	}

	@Override
	protected void onStop() {
		if (gpsServiceBound) {
			unbindService(gpsConnection);
			gpsServiceBound = false;
		}
		super.onStop();
	}

	private ServiceConnection gpsConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			gpsServiceBound = false;
			// common.displayToast("GetLocation unbound");
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			gpsService = ((GetLocation.LocalBinder) service).getService();
			// common.displayToast("GetLocation bound");
			gpsServiceBound = true;
		}
	};

	private void sendLocInfoToServer() {
		setProgressBarIndeterminateVisibility(true);		
		refreshTextFields();

		String gpsData = editTextLat.getText().toString() + ','
				+ editTextLon.getText().toString();
		Long timeStamp = System.currentTimeMillis();

		DataFromDevice dataFromDevice = new DataFromDevice(common.getDeviceType(),
				common.getSenderID(), common.getSerialNumber(), gpsData, timeStamp,
				Common.COMMAND_STORE_GPS_DATA);
		commServiceIntent.putExtra("dataFromDevice", dataFromDevice);
		commServiceIntent.putExtra("serverAddress", common.getServerAddress());
		commServiceIntent.putExtra("startingMessage",
				getString(R.string.message_location_sending_started));

		startService(commServiceIntent);
	}

	private void refreshTextFields() {
		editTextSenderID.setText(common.getSenderID());
		editTextSerialNumber.setText(common.getSerialNumber());
		editTextServerAddress.setText(common.getServerAddress());
	}

	private BroadcastReceiver locationSentReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			setProgressBarIndeterminateVisibility(false);			
		}
	};
	
	private BroadcastReceiver commServiceError = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			setProgressBarIndeterminateVisibility(false);
			common.displayToast("Commservice error");
		}
	};
}
